package com.yzt.insys.control;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.yzt.insys.beans.Info;
import com.yzt.insys.service.InfoService;
@Scope("prototype")
@Controller
@RequestMapping("/help")
public class HelpControl extends BaseControl {

	@Resource
	private InfoService infoService;
	
	@RequestMapping(value = "/all/{masterName}")
	public synchronized String toAll(@PathVariable("masterName")String masterName) {
		reqAddAttr("info",infoService.queryByPK(1L));
		return "menu/help/all";
	}
	
	@ResponseBody
	@RequestMapping("/upd")
	public Object upd(Info info){
		return infoService.updateByPK(info);
	}
	
	@RequestMapping("/view")
	public String view(){
		reqAddAttr("info",infoService.queryByPK(1L));
		return "menu/help/view";
	}

	@ResponseBody
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public String upload(MultipartHttpServletRequest request,String editor) {
		List<MultipartFile> files = request.getFiles("file");
		String rooePath="/resources";
		String basePath=session.getServletContext().getRealPath(rooePath);
		String flg="false";
		try {
			for (MultipartFile file : files) {
				if (file.isEmpty()) {
					continue;
				}
				String suffix = file.getOriginalFilename();
				suffix = suffix.substring(suffix.lastIndexOf("."));
				String relativePath="/uploadFiles/images/";
				String fileName=UUID.randomUUID().toString()+suffix;
				FileUtils.copyInputStreamToFile(file.getInputStream(),new File(basePath+relativePath+fileName));
				flg=rooePath+relativePath+fileName;
				if(editor!=null&&editor.equals("editor")){
					flg="{\"error\":0,\"url\":\"/jeesys"+flg+"\"}";
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flg;
	}
}
